package leetcode.秋招.米哈游;

import org.junit.Test;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ：zsy
 * @date ：Created 2021/8/15 20:14
 * @description：
 */
public class Main {

    @Test
    public void Test() {
        Solution solution = new Solution();
        System.out.println(solution.restoreIpAddresses("25525522135"));
    }


    public class Solution {
        /**
         * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
         *
         *
         * @param ipStr string字符串 只包含数字的字符串
         * @return string字符串ArrayList
         */
        static final int SEG_COUNT = 4;
        ArrayList<String> ans = new ArrayList<>();
        int[] segments = new int[SEG_COUNT];
        public ArrayList<String> restoreIpAddresses (String ipStr) {
            // write code here
            segments = new int[SEG_COUNT];
            dfs(ipStr, 0, 0);
            return ans;
        }

        private void dfs(String s, int segId, int segStart) {
            if (segId == SEG_COUNT) {
                if (segStart == s.length()) {
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < SEG_COUNT; i++) {
                        builder.append(segments[i]);
                        if (i != SEG_COUNT - 1) {
                            builder.append(".");
                        }
                    }
                    ans.add(builder.toString());
                }
                return;
            }
            if (segStart == s.length()) {
                return;
            }
            if (s.charAt(segStart) == '0') {
                segments[segId] = 0;
                dfs(s, segId + 1, segStart + 1);
            }

            int addr = 0;
            for (int i = segStart; i < s.length(); i++) {
                addr = addr * 10 + (s.charAt(i) - '0');
                if (addr > 0 && addr <= 0xFF) {
                    segments[segId] = addr;
                    dfs(s, segId + 1, i + 1);
                } else {
                    break;
                }
            }
        }
    }
}
